#!/usr/bin/python3
from openpyxl import load_workbook
from openpyxl.worksheet.hyperlink import Hyperlink
import os, gc
from .Base_Plugin import Base_Plugin


class Sheet_Create_Link(Base_Plugin):
    """创建工作表目录超链接插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context

    def run(self, workspace, source):
        workbook = load_workbook(os.path.join(workspace, source))
        _directory = workbook["目录"]
        for row in _directory.rows:
            can_link = 0
            table_name = row[1].value
            if table_name != "表名" and table_name is not None:
                can_link += 1

            table_description = row[2].value
            if table_description != "所属模块" and table_description is not None:
                can_link += 1
            if can_link == 2:
                row[1].hyperlink = Hyperlink(
                    ref=f"'{table_description}'!A1)",
                    location=f"'{table_description}'!A1",
                )
                self.processed += 1

        return_val = None
        if self.processed > 0:
            saved_name = r"Linked.xlsx"
            new_path = os.path.join(workspace, saved_name)
            if os.path.exists(new_path):
                os.remove(new_path)
            workbook.save(new_path)
            return_val = saved_name
        else:
            return_val = source
        del workbook
        gc.collect()
        return return_val
